<?php

namespace app\Modules\Admin\filters;

use Yii;
use yii\base\ActionFilter;

class LoginFilter extends ActionFilter
{
    public function beforeAction($action)
    {
        if(Yii::$app->user->isGuest){
            Yii::$app->controller->redirect(['default/login']);
        }
        else{
            $controllerID = Yii::$app->controller->id;
            $actionID = Yii::$app->controller->action->id;
            $moduleID = Yii::$app->controller->module->id;
            $this->addPermission($moduleID.'/'.$controllerID.'/'.$actionID);
//            if(!Yii::$app->user->can($moduleID.'/'.$controllerID.'/'.$actionID)){
//                throw new \yii\web\UnauthorizedHttpException('对不起，您现在还没获此操作的权限');
//            }
        }
        return parent::beforeAction($action);
    }

    private function addPermission($route)
    {
        $auth = Yii::$app->authManager;
        if($auth->getPermission($route)===null){
            $permisssion = $auth->createPermission($route);
            $permisssion->description = $route;
            $auth->add($permisssion);
        }
    }
}